package sb.simple.json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.Data;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;

public class GsonTest {

    public static void main(String[] args) {
        strArray2Array();
    }


    /**字符串数组转数组对象*/
    private static void strArray2Array() {
        /*数组字符串=>List<String>*/
        String strArray = "[\"左侧\",\"右侧\",\"无\"]";
        Type typeList = new TypeToken<ArrayList<String>>() {}.getType();
        ArrayList<String> list = new Gson().fromJson(strArray, typeList);
        for (String s : list) {
            System.out.println("s(list):" + s);
        }

        /*数组字符串=>String[]*/
        Type typeStrings = new TypeToken<String[]>() {}.getType();
        String[] strings = new Gson().fromJson(strArray, typeStrings);
        for (String s : strings) {
            System.out.println("s(strings):" + s);
        }

        /*数字字符串=>int[]*/
        String intArray = "[1, 3, 5]";
        Type typeInts = new TypeToken<int[]>() {}.getType();
        int[] ints = new Gson().fromJson(intArray, typeInts);
        for (int s : ints) {
            System.out.println("s(ints):" + s);
        }

        /*浮点数字符串=>double[]*/
        String doubleArray = "[1.2, 3.4, 5.5]";
        Type typeDoubles = new TypeToken<double[]>() {}.getType();
        double[] doubles = new Gson().fromJson(doubleArray, typeDoubles);
        for (double s : doubles) {
            System.out.println("s(doubles):" + s);
        }

        /*对象数组字符串=>对象[]*/
        String infos = "[{\"title\":\"赚币和赏金可在哪查看\",\"formId\":292,\"content\":\"我的\"}, {\"title\":\"赚币有什么用？\",\"formId\":293,\"content\":\"可用于抽奖\"}, {\"title\":\"提现一般哪天处理？\",\"formId\":295,\"content\":\"每周一处理，周三到账\"}, {\"title\":\"任务审核周期多长？\",\"formId\":296,\"content\":\"一般不超过7天\"}, {\"title\":\"如何邀请好友（多选）\",\"formId\":297,\"content\":\"使用邀请码-扫描二维码-分享给好友\"}] ";
        Type type = new TypeToken<ArrayList<Info>>() {}.getType();
        Gson gson = new Gson();
        ArrayList<Info> is = gson.fromJson(infos, type);
        for (Info info : is) {
            System.out.println("info:" + info);
        }
    }

    @Data
    private static class Info {
        private String title;
        private int formId;
        private String content;
    }

}
